import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../common/utils/smart_Dialog_Helper.dart';
import '../../common/index.dart' hide SmartDialogHelper;

class CommunityController extends GetxController
    with GetTickerProviderStateMixin {
  CommunityController();

  final PostService post_service = PostService();
  final UserService user_service = UserService();

  List<PostModel> posts = [];
  Map<String, UserModel> post_users = {};
  final RxBool is_loading = true.obs;

  // 滚动位置监听
  final RxDouble scroll_offset = 0.0.obs;

  // 滚动控制器
  late final ScrollController scroll_controller;

  // 动画控制器
  late final AnimationController animation_controller;

  // 更新滚动位置
  void updateScrollOffset(double offset) {
    scroll_offset.value = offset;
  }

  // 加载所有帖子
  _init_data() async {
    try {
      is_loading.value = true;

      // 获取所有帖子
      posts = await post_service.get_all_posts();
      debugPrint("加载所有帖子: ${posts.length}");

      if (posts.isEmpty) {
        debugPrint("获取帖子列表为空，尝试重置标志并重新获取");
        Storage().set_bool(Constants.is_loading_post, false);
        posts = await post_service.get_all_posts();
      }

      // 获取帖子相关的用户信息
      for (var post in posts) {
        final user = user_service.get_user_data_by_id(post.user_id);
        if (user != null) {
          post_users[post.user_id] = user;
        }
      }

      // 过滤掉被当前用户举报的帖子
      final reportedPosts = Storage().get_list(
        "${Constants.reported_posts}_${user_service.get_now_user()?.name}",
      );
      debugPrint("被举报的帖子: $reportedPosts");
      posts = posts
          .where((post) => !reportedPosts.contains(post.post_id))
          .toList();

      posts.sort((a, b) {
        // 首先按照帖子类型排序（自定义/默认）
        bool aIsDefault = int.tryParse(a.post_id) != null;
        bool bIsDefault = int.tryParse(b.post_id) != null;

        if (aIsDefault && !bIsDefault) {
          // a是默认帖子，b是用户帖子，b应该排在前面
          return 1;
        } else if (!aIsDefault && bIsDefault) {
          // a是用户帖子，b是默认帖子，a应该排在前面
          return -1;
        } else {
          // 都是默认帖子或都是用户帖子，按时间排序（新的在前）
          // 尝试解析为毫秒时间戳格式
          if (int.tryParse(a.post_created_time) != null &&
              int.tryParse(b.post_created_time) != null) {
            return int.parse(
              b.post_created_time,
            ).compareTo(int.parse(a.post_created_time));
          }
          // 默认降序排列（最新的在前面）
          return b.post_created_time.compareTo(a.post_created_time);
        }
      });

      is_loading.value = false;

      animation_controller.forward();
    } catch (e) {
      debugPrint('加载帖子数据错误: $e');
      is_loading.value = false;
    }
    update(["community"]);
  }

  // 处理点赞
  void toggle_like(String postId) async {
    final currentUser = user_service.get_now_user();

    if (currentUser == null) {
      SmartDialogHelper.show_warning('please login first before liking');
      RouteUtil.go(RouteNames.login);

      return;
    }

    final likes = currentUser.like_lists ?? [];
    List<String> updatedLikes = [];

    if (likes.contains(postId)) {
      updatedLikes = likes.where((id) => id != postId).toList();
    } else {
      updatedLikes = [...likes, postId];
    }

    final updatedUser = currentUser.copyWith(like_lists: updatedLikes);
    user_service.set_user(updatedUser);

    update(["community", "post_detail"]);
  }

  // 检查用户是否已点赞
  bool is_liked(String postId) {
    final currentUser = user_service.get_now_user();
    if (currentUser != null && currentUser.like_lists != null) {
      return currentUser.like_lists!.contains(postId);
    }
    return false;
  }

  void onTap() {}

  // 刷新帖子列表
  void refresh_posts() {
    is_loading.value = true;
    Storage().set_bool(Constants.is_loading_post, false);

    animation_controller.reset();

    _init_data();
    update(["community"]);
  }

  @override
  void onInit() {
    super.onInit();
    // 初始化动画控制器
    animation_controller = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 1500),
    );

    // 初始化滚动控制器
    scroll_controller = ScrollController();
    scroll_controller.addListener(() {
      updateScrollOffset(scroll_controller.offset);
    });
  }

  @override
  void onReady() {
    super.onReady();
    _init_data();
  }

  @override
  void onClose() {
    // 释放动画控制器
    animation_controller.dispose();
    // 释放滚动控制器
    scroll_controller.dispose();
    super.onClose();
  }

  // 计算斐波那契数列
  int calculateFibonacci(int n) {
    if (n <= 0) return 0;
    if (n == 1) return 1;
    return calculateFibonacci(n - 1) + calculateFibonacci(n - 2);
  }
}
